<?php
/**
 * User: 昊天||597767865@qq.com
 * Date: 2019/8/15
 * Time: 11:02
 */

namespace backend\controllers;

use backend\models\Oplog;
use backend\models\Role;
use backend\models\Route;
use yii\web\Controller;
use Yii;

class BaseController extends Controller
{
    public $pageSize = 15;

    public function beforeAction($action)
    {
        if (Yii::$app->user->isGuest) {
            $this->redirect(['site/login']);
            return false;
        }
        $role = Role::findOne(Yii::$app->user->identity->role_id);
        $permission = json_decode($role->jurisdiction);
        $routes = Route::find()->where(['in', 'id', $permission])->andWhere(['is_show' => 1])->asArray()->all();
        $permissionArr = array_column($routes, 'route');
        $allRoute = ['index/index', 'index/console', 'index/home', 'index/clear-cache'];
        $route = $this->route;
        if (!in_array($route, $allRoute) && !in_array($route, $permissionArr)) {
            $this->json(100, '你没有该权限操作!!');
        }

        if (!in_array($route, $allRoute) && !in_array($this->action->id, ['index', 'list'])) {
            $Route = Route::findOne(['route'=>$route]);
            Oplog::opLog(Yii::$app->user->getId(),$route,$Route->route_name,$_REQUEST);
        }
        return parent::beforeAction($action);
    }

    public function json($status = '', $msg = '', $data = '')
    {
        $arr = ['status' => $status, 'msg' => $msg];
        if (!empty($data)) {
            $arr['data'] = $data;
        }
        exit(json_encode($arr, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 列表返回
     * @param string $code
     * @param string $msg
     * @param string $count
     * @param string $data
     */
    public function api($code = '0', $msg = '', $count = '', $data = '')
    {
        $arr = ['code' => $code, 'msg' => $msg, 'count' => $count, 'data' => $data];
        exit(json_encode($arr, JSON_UNESCAPED_UNICODE));
    }

}
